<template>
  <div class="home">
    <div class="content">
      <div class="header">
        <el-page-header content="编辑页面" @back="goBack"></el-page-header>
      </div>
      <div class="selectMoudle">
        <div>
          <span class="text">模块</span>
          <el-radio-group v-model="radio1" fill="#1d2f70">
            <el-radio-button v-for="(item, index) in radio" :label="item.label" :key="index"></el-radio-button>
          </el-radio-group>
        </div>
        <div>
          <el-button class="sendBtn" @click="send">
            发布
            <i class="el-icon-upload el-icon--right"></i>
          </el-button>
        </div>
      </div>
      <div class="Imagetitele">
        <div class="textSize">添加题图</div>
      </div>
      <div class="titleImage">
        <div class="algin">
          <el-upload
            accept="image/png, image/jpg, image/jpeg"
            class="avatar-uploader"
            :action="api.imgManage"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="headers"
          >
            <img v-if="editorData.articleimg" :src="editorData.articleimg" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
      </div>
      <div class="inputBox">
        <input type="text" placeholder="输入标题" v-model="editorData.articlename" />
      </div>
      <div class="editor">
        <textEditor
          @EditorChange="editorChange"
          @uploadImageChange="uploadImageChange"
          :oldcontent="editorData.content"
          :oldremoveIds="editorData.deleImgId"
        ></textEditor>
      </div>
    </div>
  </div>
</template>

<script>
// import axios from "axios";
import textEditor from "@/components/quillEditor";
import { textReplace } from "@/common/textReplace";
import {
  get_articleOnlineDraft,
  put_articleOnlineDraft,
  delete_articleOnlineDraft
} from "@/api/articleOnlineDraft";
import { put_article } from "@/api/article";
import { post_delectImg } from "@/api/deleteTheInterface";
import { rich_text_img, rich_text_img_prefix } from "@/utils/global";
export default {
  name: "Editor",
  data() {
    return {
      editorData: {
        articleId: "", //文章id
        articlename: "", //文章标题
        articleimg: "", //文章主图
        content: "", //富文本内容
        userid: "", //用户id
        deleImgId: [], //需要删除的图片
        deletTitleImageUrl: [] //需要删除的题图图片
      },
      headers: { Authorization: "Bearer " + this.$store.getters.token },
      timer: null,
      radio1: "创新建议",
      radio: [
        {
          name: "创新建议",
          label: "创新建议"
        }
      ],
      api: {
        imgManage: rich_text_img,
        rich_text_img_prefix
      }
    };
  },
  components: {
    textEditor
  },
  async created() {
    console.log(this.$route.query._id);

    if (!this.$route.query._id) {
      this.$router.push({
        path: "/home"
      });
      return;
    }
    let editData = await get_articleOnlineDraft({
      query: { _id: this.$route.query._id }
    });
    console.log("editData", editData.data[0]);
    this.editorData = editData.data[0];
    this.$message({
      showClose: true,
      message: "已自动保存成功至草稿箱",
      type: "success"
    });
    clearInterval(this.timer);
    this.timer = null;
    this.setTimer();
  },
  destroyed: function() {
    // 每次离开当前界面时，清除定时器
    clearInterval(this.timer);
    this.timer = null;
  },
  methods: {
    setTimer() {
      let time = 1000 * 30;
      if (this.timer == null) {
        this.timer = setInterval(async () => {
          await put_articleOnlineDraft({
            query: { _id: this.editorData._id },
            update: {
              $set: this.editorData
            }
          });
          this.$message({
            showClose: true,
            message: "自动保存成功",
            type: "success"
          });
        }, time);
      }
    },
    async uploadImageChange() {
      await put_articleOnlineDraft({
        query: { _id: this.editorData._id },
        update: {
          $set: this.editorData
        }
      });
      this.$message({
        showClose: true,
        message: "自动保存成功",
        type: "success"
      });
    },
    goBack() {
      this.$router.go(-1);
    },
    handleAvatarSuccess(res, file) {
      console.log("handleAvatarSuccess", file, this.editorData);

      // this.editorData.titleImageUrl = URL.createObjectURL(file.raw);
      if (this.editorData.articleimg) {
        let name = this.editorData.articleimg.replace(
          this.api.rich_text_img_prefix,
          ""
        );
        this.editorData.deletTitleImageUrl.push(name);
      }
      this.editorData.articleimg = file.response.url;
      this.uploadImageChange();
      console.log("handleAvatarSuccess2222", this.editorData);
    },
    // uploadSectionFile: function(param) {
    //   //自定义文件上传
    //   console.log("param", param);
    //   // var fileObj = param.file;
    //   var reader = new FileReader(); //调用FileReader
    //   reader.readAsDataURL(param.file); //将文件读取为 DataURL(base64)
    //   var that = this;
    //   reader.onload = function(evt) {
    //     //读取操作完成时触发。
    //     that.editorData.titleImageUrl = evt.target.result;
    //   };
    // },
    editorChange(data) {
      this.editorData.content = data.html;
      if (this.editorData.deleImgId.length != data.removeIds.length) {
        this.uploadImageChange();
      }
      this.editorData.deleImgId = data.removeIds;
      // this.editorData.textReplace = textReplace(data.html);
      console.log("改变后", this.editorData);
    },
    async send() {
      if (this.editorData.articleimg == "") {
        return this.$alert("请添加题图", "提示", {
          confirmButtonText: "确定",
          callback: () => {}
        });
      }
      if (this.editorData.articlename == "") {
        return this.$alert("请完善文章标题", "提示", {
          confirmButtonText: "确定",
          callback: () => {}
        });
      }
      if (this.editorData.content == "") {
        return this.$alert("请完善文章内容", "提示", {
          confirmButtonText: "确定",
          callback: () => {}
        });
      }
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let deleArr = this.editorData.deleImgId.concat(
        this.editorData.deletTitleImageUrl
      );
      console.log(deleArr);
      let replaceText = textReplace(this.editorData.content);
      await put_article({
        query: { _id: this.editorData.articleId },
        update: {
          $set: {
            audit: false,
            articlename: this.editorData.articlename, //文章标题
            articleimg: this.editorData.articleimg, //文章主图
            content: this.editorData.content, //富文本内容
            textReplace: replaceText,
            release_time: new Date()
          }
        }
      });

      let dele = await delete_articleOnlineDraft({
        query: {
          _id: this.editorData._id
        }
      });
      console.log("dele", dele);

      if (deleArr.length != 0) {
        await post_delectImg({
          deleImgArr: deleArr
        });
      }
      setTimeout(() => {
        loading.close();
        this.$message({
          showClose: true,
          message: "发布成功",
          type: "success"
        });
        this.$alert("文章已发布，请耐心等待审核", "提示", {
          confirmButtonText: "确定",
          callback: () => {
            this.$router.go(-1);
          }
        });
        // this.$router.replace({
        //   path: "/personalCenter"
        // });
      }, 1000);
    }
  }
};
</script>

<style lang="scss" scoped>
.home {
  width: 100%;
  background: #fff;
}
.content {
  width: 100%;
  .header {
    margin: 0 auto;
    width: 1200px;
    margin-top: 20px;
  }
  .selectMoudle {
    margin: 0 auto;
    width: 1200px;
    margin-top: 40px;
    display: flex;
    justify-content: space-between;
    .text {
      font-size: 20px;
      font-weight: 700;
      color: #757575;
      margin-right: 20px;
    }
    .sendBtn {
      background: #1d2f70;
      border: #1d2f70;
      color: #fff;
      &:hover {
        background: rgb(53, 89, 180);
      }
    }
  }
  .Imagetitele {
    width: 1200px;
    margin: 0 auto;
    margin-top: 40px;
    .textSize {
      font-size: 27px;
      font-weight: 700;
      color: #757575;
    }
  }
  .titleImage {
    width: 1200px;
    margin: 0 auto;
    margin-top: 20px;
    .algin {
      width: 800px;
      margin: 0 auto;
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 800px;
        height: 300px;
        line-height: 300px;
        text-align: center;
      }
      .avatar {
        width: 800px;
        display: block;
      }
    }
  }
  .inputBox {
    margin: 0 auto;
    width: 1200px;
    margin-top: 20px;
    input {
      outline-style: none;
      outline-style: none;
      border: 0px;
      border-bottom: 2px solid #ccc;
      width: 1200px;
      padding: 13px 14px;
      font-size: 28px;
      font-weight: 700;
      font-family: "Microsoft soft";
      box-sizing: border-box;
    }
  }
  // margin-top: -19px;
  padding: 20px;
  box-sizing: border-box;
  .editor {
    min-height: 500px;
    margin-top: 40px;
  }
}
</style>
